package hello.configuration.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import hello.util.JwtUtils;
import hello.util.LogManager;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @Description:
 * @Author: m01
 * @Date: created at  2018/12/20  14:51
 * @Modified By:
 */
public class AuthenticationFilter implements Filter {

    private static Logger logger;


    private Logger getLogger(String loggerName){


        Logger logger = LogManager.getLogger(loggerName);

        LogManager.setLogLevel(logger, Level.INFO);
        Handler fileHandlerOfInfo = LogManager.getFileHandler("testtask_info_.log", Level.INFO);
        Handler fileHandlerOfWarning = LogManager.getFileHandler("testtask_warning_.log", Level.WARNING);
        Handler consoleHandler = LogManager.getConsoleHandler(Level.ALL);
        ArrayList<Handler> handles = new ArrayList<Handler>();
        handles.add(fileHandlerOfInfo);
        handles.add(fileHandlerOfWarning);
        handles.add(consoleHandler);
        LogManager.setHandler(logger, handles);
        return logger;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        System.out.println("AllowCrossOriginFilter  init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {


        if (logger == null) {
            logger = getLogger(AuthenticationFilter.class.getName());
        }


        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String jwttoken = request.getHeader("jwttoken");

        Jws<Claims> claimsJws = JwtUtils.parseJWT(jwttoken);
        if (claimsJws != null) {
            logger.info(request.getSession().getId()+"  "+claimsJws.getBody().get("username")+"  成功访问");
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            Map<String, String> result = new HashMap<>();
            result.put("code", "404");
            logger.info(request.getSession().getId()+ " 失败访问");
            responseWrite(result, response);
            return;

        }


    }

    @Override
    public void destroy() {
        System.out.println("AllowCrossOriginFilter  destory");

    }


    private static String convertObjectToJson(Object object) throws JsonProcessingException {
        if (object == null) {
            return null;
        }
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(object);
    }


    private static void responseWrite(Map<String, String> map, HttpServletResponse response) throws IOException {
        response.setContentType("application/json; charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        String userJson = convertObjectToJson(map);
        OutputStream out = response.getOutputStream();
        out.write(userJson.getBytes("UTF-8"));
    }

}
